<template>
  <div class="xiecheng">
    <div class="admin_main_block">
      <div class="admin_main_block_top">
        <div class="admin_main_block_left">
          <div>{{ i18n('business.publish.template.schedule.form') }}</div>
        </div>

        <div class="admin_main_block_right">
          <div>
            <el-button icon="Back" @click="router.go(-1)">
              {{ i18n('common.return') }}
            </el-button>
          </div>
        </div>
      </div>

      <div class="admin_form_main">

          <el-row :gutter="20">
            <el-col :span="8">
              <schedule-vue />
            </el-col>
            <el-col :span="8">
              <schedule-vue />
            </el-col>
          </el-row>






        <el-form label-width="120px" ref="formRef" :model="dataForm" :rules="dataRule" v-loading="formLoading" element-loading-text="Submitting...">








          <!-- <el-card class="publish-time-card" shadow="hover">
            <div class="text item">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item :label="$t('business.publish.template.schedule.publish_time')" prop="publish_time">
                    <el-date-picker class="input" v-model="dataForm.publish_time" type="date" :disabled-date="disabledDate"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="16" align="right">
                  <el-form-item label-width="0">
                    <el-button class="button" type="success" @click="addGroupOption(dataForm)">{{ $t('business.publish.template.schedule.add_group') }}</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-card>


          <view v-for="(group, k1) in dataForm.group" :key="k1">
            <el-card class="group-card" shadow="hover">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item :label="$t('business.publish.template.schedule.group_title')" prop="group_title">
                    <el-input class="input" v-model="group.group_title" :placeholder="$t('common.please_input')+$t('business.publish.template.schedule.group_title')" clearable></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="16" align="right">
                  <el-form-item label-width="0">
                    <el-button class="button" :type="group.show ? 'info' : 'primary'" @click="handleGroup(group)">{{ group.show ? '折叠' : '展开' }}</el-button>

                    <el-button class="button" type="danger" @click="removeGroupOption(dataForm, group)" v-if="dataForm.group.length != 1">{{ $t('business.publish.template.schedule.remove_group') }}</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>

            <view v-if="group.show">
              <el-card class="schedule-card" shadow="hover" v-for="(item, index) in group.schedule" :key="index">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item :label="$t('business.publish.template.schedule.machine_id')" prop="machine_id">
                      <el-select class="input" v-model="item.machine_id" :placeholder="$t('common.please_select')+$t('business.publish.template.schedule.machine_id')" clearable>
                        <el-option v-for="(v,k) in machineList" :label="v.title" :key="k" :value="v.id"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item :label="$t('business.publish.template.schedule.ship_name')" prop="ship_name">
                      <el-input class="input" v-model="item.ship_name" :placeholder="$t('common.please_input')+$t('business.publish.template.schedule.ship_name')" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item :label="$t('business.publish.template.schedule.voyage_number')" prop="voyage_number">
                      <el-input class="input" v-model="item.voyage_number" :placeholder="$t('common.please_input')+$t('business.publish.template.schedule.voyage_number')" clearable></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <view class="line-top"></view>

                <view class="route" v-for="(route, key) in item.route" :key="key">
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <el-form-item :label="$t('business.publish.template.schedule.harbor_type')" prop="harbor_type">
                        <el-radio-group class="input" v-model="route.harbor_type">
                          <el-radio :label="1">{{ $t('business.container.schedule.log.start_code') }}</el-radio>
                          <el-radio :label="2">{{ $t('business.container.schedule.log.end_code') }}</el-radio>
                          <el-radio :label="3">{{ $t('business.publish.template.schedule.use_common') }}</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item :label="$t('business.publish.template.schedule.harbor_code')" prop="harbor_code">
                        <el-select class="input" v-model="route.harbor_code"  :placeholder="$t('common.please_select')+$t('business.publish.template.schedule.harbor_code')" :remote-method="loadHarborList" :loading="loading" @visible-change="loadDefaultHarborList()" reserve-keyword filterable remote clearable>
                          <el-option v-for="(v, k) in harborList" :label="v.english_name" :key="k" :value="v.code"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item :label="$t('business.publish.template.schedule.transit_time')" prop="transit_time">
                        <el-date-picker class="input" v-model="route.transit_time" type="daterange" :range-separator="$t('business.publish.template.schedule.to')" :start-placeholder="$t('business.publish.template.schedule.start_time')" :end-placeholder="$t('business.publish.template.schedule.end_time')">
                        </el-date-picker>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20" v-if="(route.harbor_type == 2 || route.harbor_type == 3) && route.is_price == 1">
                    <el-col :span="8">
                      <el-form-item :label="$t('business.publish.template.schedule.vehicle')" prop="price1">
                        <el-input class="input" v-model="route.price1"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item :label="$t('business.publish.template.schedule.equipment')" prop="price2">
                        <el-input class="input" v-model="route.price2"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item :label="$t('business.publish.template.schedule.steel')" prop="price3">
                        <el-input class="input" v-model="route.price3"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="20">
                    <el-col :span="8" v-if="(route.harbor_type == 2 || route.harbor_type == 3) && route.is_price == 1">
                      <el-form-item :label="$t('business.publish.template.schedule.ton_bag')" prop="price4">
                        <el-input class="input" v-model="route.price4"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8" v-if="(route.harbor_type == 2 || route.harbor_type == 3)">
                      <el-form-item :label="$t('business.publish.template.schedule.is_price')" prop="is_price">
                        <el-radio-group class="input" v-model="route.is_price">
                          <el-radio :label="1">{{ $t('business.publish.template.schedule.show') }}</el-radio>
                          <el-radio :label="0">{{ $t('business.publish.template.schedule.hidden') }}</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8" class="route-button">
                      <el-button class="button" type="success" @click="addRouteOption(item)" v-if="key == (item.route.length - 1)">{{ $t('business.publish.template.schedule.add_route') }}</el-button>
                      <el-button class="button" type="danger" @click="removeRouteOption(item, route)" v-if="item.route.length != 1">{{ $t('business.publish.template.schedule.remove_route') }}</el-button>
                    </el-col>
                  </el-row>

                  <view class="line-bottom"></view>
                </view>

                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item :label="$t('business.publish.template.schedule.disclaimer')" prop="disclaimer">
                      <el-input class="textarea" type="textarea" v-model="item.remark.disclaimer"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-form-item :label="$t('business.publish.template.schedule.remark')" prop="remark">
                      <el-input class="textarea" type="textarea" v-model="item.remark.remark"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item :label="$t('business.publish.template.schedule.manager_id')" prop="manager_id">
                      <el-select class="input" v-model="item.manager_id" :placeholder="$t('common.please_select')+$t('business.publish.template.schedule.manager_id')" filterable multiple collapse-tags :multiple-limit="4" clearable>
                        <el-option v-for="(v,k) in managerList" :label="v.title" :key="k" :value="v.id"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <view class="line"></view>

                <el-row :gutter="20">
                  <el-col :span="8" class="route-button">
                    <el-button class="button" type="success" @click="addScheduleOption(group)" v-if="index == (group.schedule.length - 1)">{{ $t('business.publish.template.schedule.add_schedule') }}</el-button>
                    <el-button class="button" type="danger" @click="removeScheduleOption(group, item)" v-if="group.schedule.length != 1">{{ $t('business.publish.template.schedule.remove_schedule') }}</el-button>
                  </el-col>
                </el-row>
              </el-card>
            </view>
          </view> -->

          <el-card class="submit-card mt10" shadow="hover">
            <el-form-item>
              <el-button
                v-if="isAuth('module:business:publish:template:schedule:handle')"
                type="primary"
                @click="dataFormSubmit(formRef)">
                {{ i18n('common.confirm') }}
              </el-button>
              <el-button @click="resetForm(formRef)">
                {{ i18n('common.reset') }}
              </el-button>
            </el-form-item>
          </el-card>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup name="business-publish-template-schedule-form">
  import { useBase } from '@/hooks/base/useBase'
  import { useForm } from '@/hooks/form/useForm'
  import { isEmpty } from '@/utils/validate'

  import ScheduleVue from '@/components/publish/template/schedule'

  const { router, query, i18n, isAuth } = useBase()

  const model = ref('business/publish/template/schedule')

  const machineList = ref([])
  const managerList = ref([])
  const harborList = ref([])
  const loading = ref(false)
  const formLoading = ref(false)

  const dataForm = reactive({
    organization_id: 0,
    shipowner_id: 0,
    template_id: 0,
    publish_time: '',
    group: [{
      id: '',
      group_title: '',
      show: false,
      schedule: [{
        id: '',
        machine_id: '',
        ship_name: '',
        voyage_number: '',
        route: [{
          harbor_code: '',
          transit_time: '',
          harbor_type: 1,
          is_price: 0,
          price1: '',
          price2: '',
          price3: '',
          price4: '',
        }],
        remark: {
          disclaimer: '',
          remark: '',
        },
        manager_id: [],
      }]
    }]
  })

  const dataRule = reactive({
    publish_time: [{
      required: true,
      message: i18n('business.publish.template.schedule.rules.publish_time.require'),
      trigger: 'blur',
    }],
  })


  const schedule = ref([{
    id: '',
    machine_id: '',
    ship_name: '',
    voyage_number: '',
    route: [{
      harbor_code: '',
      transit_time: '',
      harbor_type: 1,
      is_price: 0,
      price1: '',
      price2: '',
      price3: '',
      price4: '',
    }],
    remark: {
      disclaimer: '',
      remark: '',
    },
    manager_id: [],
  }])




  const {
    formRef,
    resetForm
  } = useForm(model.value, dataForm)


  // 获取运输工具数据
  const loadMachineList = () => {
    $http({
      url: $http.adornUrl(`/business/information/machine/select`),
      method: 'get',
      params: $http.adornParams({
        category_id: 1
      }),
    }).then(({ data }) => {
      if (data && data.status === 200) {
        machineList.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }


  // 获取运输工具数据
  const loadManagerList = () => {
    $http({
      url: $http.adornUrl(`/business/manager/select`),
      method: 'get',
      params: $http.adornParams({
        shipowner_id: dataForm.shipowner_id
      }),
    }).then(({ data }) => {
      if (data && data.status === 200) {
        managerList.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }


  const loadDefaultHarborList = () => {
    $http({
      url: $http.adornUrl(`/business/publish/template/harbor/select`),
      method: 'get',
      params: $http.adornParams({
        shipowner_id: dataForm.shipowner_id
      }),
    }).then(({ data }) => {
      if (data && data.status === 200) {
        harborList.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }


  // 获取航线所属港口数据
  const loadHarborList = (name) => {
    if (name) {
      $http({
        url: $http.adornUrl(`/business/publish/template/harbor/select`),
        method: 'get',
        params: $http.adornParams({
          shipowner_id: dataForm.shipowner_id,
          keyword: name,
        }),
      }).then(({ data }) => {
        if (data && data.status === 200) {
          harborList.value = data.data
        } else {
          $message.error(data.message)
        }
      })
    } else {
      harborList.value = []
    }
  }


  const init = (form) => {
    nextTick(() => {
      form.value.resetFields()
      if (dataForm.shipowner_id) {
        $http({
          url: $http.adornUrl(`/${model.value}/data`),
          method: 'get',
          params: $http.adornParams({
            shipowner_id: dataForm.shipowner_id,
            template_id: dataForm.template_id
          }),
        }).then(({ data }) => {
          if (data && data.status === 200 && data.data.shipowner_id) {
            dataForm.organization_id = data.data.organization_id
            dataForm.shipowner_id = data.data.shipowner_id
            dataForm.template_id = data.data.template_id
            dataForm.publish_time = data.data.publish_time
            dataForm.group = data.data.group
          }
        })
      }
    })
  }


  // 船期信息发布
  const dataFormSubmit = (form) => {
    formLoading.value = true

    form.validate(async (valid, fields) => {
      if (valid) {
        $http({
          url: $http.adornUrl(`/${model.value}/handle`),
          method: 'post',
          data: $http.adornData({
            organization_id: dataForm.organization_id,
            shipowner_id: dataForm.shipowner_id,
            template_id: dataForm.template_id,
            publish_time: dataForm.publish_time,
            group: dataForm.group,
          }),
        }).then(({ data }) => {
          formLoading.value = false

          if(data && data.status == 200) {
            init(formRef)
          } else {
            $message.error(data.message)
          }
        })
      }
    })
  }


  // 分组显示操作
  const handleGroup = (group) => {
    group.show = !group.show

    if(isEmpty(group.title)) {
      return false
    }
  }


  // 添加航线选项组
  const addGroupOption = (data) => {
    // 校验
    if (data.group.length > 0) {
      let option = data.group[data.group.length - 1]
      if (isEmpty(option.group_title)) {
        $message.error(i18n('common.please_select') + i18n('business.publish.template.schedule.group_title'));
        return
      }
      data.group.push({ id: '', group_title: '', show: false, schedule: [{ id: '', machine_id: '', title: '', voyage_number: '', route: [{ harbor_code: '', transit_time: '', harbor_type: 1, is_price: 0, price1: '', price2: '', price3: '', price4: '' }], remark: {disclaimer: '', remark: ''}, manager_id: []}] })
    } else {
      data.group.push({ id: '', group_title: '', show: false, schedule: [{ id: '', machine_id: '', title: '', voyage_number: '', route: [{ harbor_code: '', transit_time: '', harbor_type: 1, is_price: 0, price1: '', price2: '', price3: '', price4: '' }], remark: {disclaimer: '', remark: ''}, manager_id: []}] })
    }
  }

  // 删除航线选项组
  const removeGroupOption = (data, item) => {
    let index = data.group.indexOf(item)
    if (index !== -1) {
      data.group.splice(index, 1)
    }
  }

  // 添加船期选项组
  const addScheduleOption = (data) => {
    // 校验
    if (data.schedule.length > 0) {
      let option = data.schedule[data.schedule.length - 1]
      if (isEmpty(option.machine_id)) {
        $message.error(i18n('common.please_select') + i18n('business.publish.template.schedule.machine_id'));
        return
      }
      data.schedule.push({ id: '', machine_id: '', title: '', voyage_number: '', route: [{ harbor_code: '', transit_time: '', harbor_type: 1, is_price: 0, price1: '', price2: '', price3: '', price4: '' }], remark: {disclaimer: '', remark: ''}, manager_id: [] })
    } else {
      data.schedule.push({ id: '', machine_id: '', title: '', voyage_number: '', route: [{ harbor_code: '', transit_time: '', harbor_type: 1, is_price: 0, price1: '', price2: '', price3: '', price4: '' }], remark: {disclaimer: '', remark: ''}, manager_id: [] })
    }
  }

  // 删除船期选项组
  const removeScheduleOption = (data, item) => {
    let index = data.schedule.indexOf(item)
    if (index !== -1) {
      data.schedule.splice(index, 1)
    }
  }

  // 添加港口选项组
  const addRouteOption = (data) => {
    // 校验
    if (data.route.length > 0) {
      let option = data.route[data.route.length - 1]
      if (isEmpty(option.harbor_code)) {
        $message.error(i18n('common.please_select') + i18n('business.publish.template.schedule.harbor_code'));
        return
      }
      data.route.push({ harbor_code: '', transit_time: '', harbor_type: 1, is_price: 0, price1: '', price2: '', price3: '', price4: '' })
    } else {
      data.route.push({ harbor_code: '', transit_time: '', harbor_type: 1, is_price: 0, price1: '', price2: '', price3: '', price4: '' })
    }
  }

  // 删除港口选项组
  const removeRouteOption = (data, item) => {
    let index = data.route.indexOf(item)
    if (index !== -1) {
      data.route.splice(index, 1)
    }
  }

  const disabledDate = (time) => {
    return time.getTime() >= Date.now()
  }

  onMounted(() => {
    if(query.shipowner_id) {
      dataForm.shipowner_id = parseInt(query.shipowner_id)
    }

    if(query.template_id) {
      dataForm.template_id = parseInt(query.template_id)
    }

    // init(formRef)

    // loadManagerList()
    // loadMachineList()
    // loadDefaultHarborList(false)
  })
</script>

<style lang="scss" scoped>
  .el-form-item {
    margin-bottom: 0;
  }
  .input {
    width: 90%;
  }
  .textarea {
    width: 97%;
  }

  .group-card {
    margin-bottom: 20px;
    &:nth-child(1n) {
      margin: 10px 0 10px 0;
    }
  }
</style>
